<?php
/**
 * Functions for ther page in admin.
 *
 * The manager page post type for the jamnews plugin - this file contains functions to display
 * and save the list of post type.
 *
 * @author 		VoAnhKiet
 * @category 	Admin
 * @package 	jamnews/Admin/Page
 * @version     1.6.4
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

if( ! class_exists( 'WP_List_Table' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

class jamnews_List_Posttype extends WP_List_Table{
	
	public $items = array(); 
	
	public function __construct(){
		parent::__construct( array(
			'singular'  => __( 'Jamnew', 'jamnews' ),
			'plural'    => __( 'Jamnews', 'jamnews' ),
			'ajax'      => true
		));
	}
	
	public function no_items() {
		echo __( 'No post type found!','jamnews' );
	}
	
	 function column_default( $item, $column_name ) {
		switch( $column_name ) {
			case 'name':
				return $item[ $column_name ];
			case 'description':
				$description = "<div class='posttype-description'><p>".($item[ $column_name ]!=""?$item[ $column_name ]:__("No description",'jamnews'))."</p></div>";
				$support 	 = "<div class='posttype-support'>".__("Supports",'jamnews').": <span>".implode(" | ", $item['supports'])."</span></div>";
				return $description.$support;
			case 'picon':
				$icon = ($item[ $column_name ])?wp_get_attachment_image($item[ $column_name ],"thumbnail"):"<i class='icon icon-pushpin icon-large'></i>";
				return $icon;
			case 'active':
				$icon = ( $item['active']?"icon icon-ok icon-large color-green":"icon icon-ban-circle icon-large  color-red" );
				$paged = (isset($_REQUEST['paged'])?'&paged='.$_REQUEST['paged']:'');
				return sprintf('<a href="?page=%s&action=%s&id=%s%s"><i class="%s"></i></a>',$_REQUEST['page'], ( $item['active']?"deactive":"active" ), $item['id'],$paged ,$icon);
			default:
				return print_r( $item, true ) ;
		}
	}
	
	function get_sortable_columns() {
	  $sortable_columns = array(
		'name'  => array('name',false),
		'active' => array('active',false)
	  );
	  return $sortable_columns;
	}
 
 
	public function get_columns(){
		$columns = array(
			'cb'        => '<input type="checkbox" />',
			'picon'      => __( 'Icon', 'jamnews' ),
			'name' => __( 'Name', 'jamnews' ),
			'description'    => __( 'Description', 'jamnews' ),
			'active'		=> __( 'Status' , 'jamnews')
		);
		return $columns;
	}
	
	public function usort_reorder( $a, $b ) {
		// If no sort, default to title
		$orderby = ( ! empty( $_GET['orderby'] ) ) ? $_GET['orderby'] : 'name';
		// If no order, default to asc
		$order = ( ! empty($_GET['order'] ) ) ? $_GET['order'] : 'asc';
		// Determine sort order
		$result = strcmp( $a[$orderby], $b[$orderby] );
		// Send final sort direction to usort
		return ( $order === 'asc' ) ? $result : -$result;
	}
	
	public function column_name($item){
		$active = ( $item['active']?"deactive":"active" );
		$class = ( $item['active']?"active":"deactive" );
		$label_active = ( $item['active']?__("Deactive","jamnews"):__("Active","jamnews") );
		$paged = (isset($_REQUEST['paged'])?'&paged='.$_REQUEST['paged']:'');
		$actions = array(
			'status' => sprintf('<a href="?page=%s&action=%s&id=%s%s">%s</a>',$_REQUEST['page'], $active, $item['id'],$paged,$label_active),
			'edit' => sprintf('<a href="?page=%s&action=%s&id=%s">Edit</a>',$_REQUEST['page'],'edit',$item['id']),
			'delete'=> sprintf('<a href="?page=%s&action=%s&id=%s%s">Delete</a>',$_REQUEST['page'],'delete',$item['id'],$paged),
		);
		return sprintf( '<a class="row-title %1$s" href="?page=%2$s&action=%3$s&id=%4$s">%5$s</a> - %6$s %7$s',$class, $_REQUEST['page'],'edit',$item['id'],$item['name'],$item['post_type'],$this->row_actions($actions) );
	}
 
	public function get_bulk_actions() {
	  $actions = array(
		'delete'    => __('Delete','jamnews'),
		'active'	=> __('Active','jamnews'),
		'deactive' => __('Deactive','jamnews'),
	  );
	  return $actions;
	}
 
	public function column_cb($item) {
		return sprintf('<input type="checkbox" name="id[]" value="%s" />', $item['id']);    
	}
	
	 
	public function prepare_items() {
		global $jamnews;
		$post_types = $jamnews->db_get_post_types();
		foreach($post_types as $key => $post_type){
			$label = $post_type->meta_value['label'];
			if($labels = $post_type->meta_value['labels'] && $post_type->meta_value['labels']['name']!=""){
				
			}
			$this->items[] = array(
				'id' => $post_type->id,
				'picon' => $post_type->meta_value['menu_icon'],
				'name' => $label,
				'post_type' => $post_type->meta_key,
				'description' => $post_type->meta_value['description'],
				'active' => ($post_type->status==1)?true:false,
				'supports' => $post_type->meta_value['supports']
			);
		}
		
		$columns  = $this->get_columns();
		$hidden   = array();
		$sortable = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );
		usort( $this->items, array( &$this, 'usort_reorder' ) );

		$per_page = 2;
		$current_page = $this->get_pagenum();
		$total_items = count( $this->items );

		// only ncessary because we have sample data
		$this->found_data = array_slice( $this->items,( ( $current_page-1 )* $per_page ), $per_page );

		$this->set_pagination_args( array(
			'total_items' => $total_items,
			'per_page'    => $per_page
		) );
		$this->items = $this->found_data;
	}
 
} // End class jamnews_List_Posttype


/**
 * Load Default field in groups/fields manager.
 *
 * @access public
 * @return void
 */
function jamnews_load_default_fields($fields) {
	global $jamnews;
	require_once $jamnews->plugin_path()."/classes/jamfield_text.php";
	$fields[] = new JamField_Text();
	return $fields;
}
add_filter("jamnews_fields","jamnews_load_default_fields");

/**
 * Admin page.
 *
 * Handles the all of the main page in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_manager_posttypes')){
	
	function jamnews_manager_posttypes(){
	
		if( !isset( $_REQUEST['action'] ) ) $action = "list";
		if( isset( $_REQUEST['action'] ) && $_REQUEST['action'] != '-1' ) { $action = $_REQUEST['action']; }
		if( isset( $_REQUEST['action2'] ) && $_REQUEST['action2'] != '-1' ) { $action = $_REQUEST['action2']; }
		if(!$action){ $action = "list"; }
		do_action("jamnews_posttye_action_".$action);
	}
}


/**
 * Admin list post type.
 *
 * Handles the display of the list post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_posttye_action_list')){
	function jamnews_posttye_action_list(){
		global $jamnews;
		
		$table_list = new jamnews_List_Posttype();
		$table_list->prepare_items();
		?>
		<div class="wrap jamnews">
			<div id="icon-edit" class="icon32 icon32-posts-post"><br /></div>
			<h2>
				<?php echo __("Manager Post Types");?> <?php echo sprintf('<a  class="add-new-h2" href="?page=%s&action=%s">%s</a>',$_REQUEST['page'],'add',__("Add new","jamnews"))?>
			</h2>
			<form method="post" id="mainform" action="" enctype="multipart/form-data">
				<?php $table_list->display();?>
			</form>
		
		</div>
		<?php
	}
	add_action("jamnews_posttye_action_list","jamnews_posttye_action_list");
}


/**
 * Admin insert new post type.
 *
 * Handles the insert new the post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_posttye_action_add')){
	function jamnews_posttye_action_add(){
		global $jamnews;
		
		// Save post type
		require_once $jamnews->plugin_path()."/admin/form-insert-posttype.php";
		do_action( "jamnews_save_posttype" );
		form_insert_post_type();
	}
	add_action("jamnews_posttye_action_add","jamnews_posttye_action_add");
}

/**
 * Admin insert new post type.
 *
 * Handles the insert new the post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_save_posttype')){
	function jamnews_save_posttype(){
		global $jamnews;
		if(!wp_verify_nonce($_POST['_wpnonce'],'jamnews_admin_save_posttype')) return;
		$post_type = $_POST['post_type'];
		if( $post_type == '' ) return;
		
		// Default posttype
		$args = array(
			'label'					=> ($_POST['label']=='')?$post_type:$_POST['label'],
			'supports' 				=> array_keys($_POST['supports']),
			'description'			=> $_POST['description'],
			'public' 				=> true,
			'exclude_from_search' 	=> false,
			'publicly_queryable' 	=> false,
			'show_ui' 				=> false,
			'show_in_nav_menus' 	=> false,
			'show_in_menu' 			=> false,
			'show_in_admin_bar' 	=> false,
			'map_meta_cap' 			=> false,
			'hierarchical' 			=> false,
			'can_export' 			=> false,
			'_builtin' 				=> false,
			'_edit_link' 			=> false,
			'query_var' 			=> false,
			'has_archive' 			=> false,
			'permalink_epmask' 		=> false,
			'rewrite' => array(
				  'with_front' => false,
				  'feeds' => false,
				  'pages' => false,
			)
		);
		if( isset($_POST['taxonomies']) && !empty($_POST['taxonomies']) ){
			$args['taxonomies'] = $_POST['taxonomies'];
		}
		
		if($id=$_REQUEST['id']){
			// Public
			if( !$_POST['public'] ){
				$args['public'] = false;
			}
			
			// Get labels
			$temps = array(
				'name','singular_name','menu_name','all_items','add_new',
				'add_new_item','edit_item','new_item','view_item','search_items',
				'not_found','not_found_in_trash','parent_item_colon ');
			foreach($temps as $index){
				if(isset($_POST['labels'][$index]) && $_POST['labels'][$index]!=""){
					$args['labels'][$index] = $_POST['labels'][$index];
				}
			}
			
			// Get value true|false
			$temps = array( 
				'exclude_from_search', 'publicly_queryable', 'show_ui',
				'show_in_nav_menus', 'show_in_menu', 'show_in_admin_bar', 
				'map_meta_cap','hierarchical', 'can_export', '_builtin', '_edit_link' );
			foreach($temps as $index){
				$args[$index] = (isset($_POST[$index]) && $_POST[$index]=='1')?true:false;
			}
			
			// Get value string|false
			$temps = array('query_var','has_archive','permalink_epmask');
			foreach($temps as $index){
				$args[$index] = (!isset($_POST[$index]) || $_POST[$index]=="")?false:$_POST[$index];
			}
			
			// Get value string|notset
			$temps = array('permalink_epmask','capability_type','menu_icon','menu_position');
			foreach($temps as $index){
				if(isset($_POST[$index]) && $_POST[$index]!="")  $args[$index] = $_POST[$index];
			}
			// Rewrite
			$temps = array('slug','ep_mask');
			foreach($temps as $index){
				if( isset($_POST['rewrite'][$index]) && $_POST['rewrite'][$index]!="") $args['rewrite'][$index] = $_POST['rewrite'][$index];
			}
			$temps = array('with_front','feeds','pages');
			foreach($temps as $index){
				$args['rewrite'][$index] = 	(isset($_POST['rewrite'][$index])&& $_POST['rewrite'][$index]=='1')?true:false;
			}
			
			// Capabilities
			$temps = array(
				'edit_post','read_post','delete_post','edit_posts','edit_others_posts',
				'publish_posts','read_private_posts','delete_posts','delete_private_posts',
				'delete_published_posts','delete_others_posts','edit_private_posts','edit_published_posts' );
			foreach($temps as $index){
				if(isset($_POST['capabilities'][$index]) && $_POST['capabilities'][$index]!=""){
					$args['capabilities'][$index] = $_POST['capabilities'][$index];
				}
			}
			
			// Update post type
			$result = $jamnews->db_update_option(array(
				"id"			=>	$id,
				"meta_key" 		=> $post_type,
				"meta_value" 	=> $args
			) );
		}else{
			$id = $jamnews->db_insert_option(array(
				"meta_key" => $post_type,
				"meta_value" => $args
			));
			if($id) wp_redirect("?page={$_REQUEST['page']}&action=edit&id={$id}");
		}
	}
	add_action("jamnews_save_posttype","jamnews_save_posttype");
}


/**
 * Admin edit post type.
 *
 * Handles the edit the post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_posttye_action_edit')){
	function jamnews_posttye_action_edit(){	
		if(!$id = intval($_REQUEST['id'])) {
			wp_redirect("?page={$_GET['page']}");
			die();
		}
		global $jamnews;
		require_once $jamnews->plugin_path()."/admin/form-update-posttype.php";
		do_action( "jamnews_save_posttype" );
		form_update_post_type($id);
	}
	add_action("jamnews_posttye_action_edit","jamnews_posttye_action_edit");
}

/**
 * Admin delete post type.
 *
 * Handles the delete the post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_posttye_action_delete')){
	function jamnews_posttye_action_delete(){
		global $jamnews;
		if($id = intval($_REQUEST['id'])){
			$jamnews->db_delete_option("id",$id);
		}
		do_action("jamnews_posttye_action_list");
	}
	add_action("jamnews_posttye_action_delete","jamnews_posttye_action_delete");
}



/**
 * Admin active post type.
 *
 * Handles the active the post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_posttye_action_active')){
	function jamnews_posttye_action_active(){
		global $jamnews;
		if(isset($_REQUEST['id']) && $_REQUEST['id']){
			$post_types = array();
			if(!is_array($_REQUEST['id'])) $post_types[] = $_REQUEST['id'];
			else $post_types = $_REQUEST['id'];
			$results = $jamnews->db_active_rows($post_types);
		}
		do_action("jamnews_posttye_action_list");
	}
	add_action("jamnews_posttye_action_active","jamnews_posttye_action_active");
}

/**
 * Admin deactive post type.
 *
 * Handles the active the post type in admin.
 *
 * @access public
 * @return void
 */
if(!function_exists('jamnews_posttye_action_deactive')){
	function jamnews_posttye_action_deactive(){
		global $jamnews;
		if(isset($_REQUEST['id'])){
			$post_types = array();
			if(!is_array($_REQUEST['id'])) $post_types[] = $_REQUEST['id'];
			else $post_types = $_REQUEST['id'];
			$results = $jamnews->db_active_rows($post_types,false);
		}
		do_action("jamnews_posttye_action_list");
	}
	add_action("jamnews_posttye_action_deactive","jamnews_posttye_action_deactive");
}


